package com.zhong.blog.controller;

import com.zhong.blog.components.JwtTokenUtil;
import com.zhong.blog.components.TokenCache;
import com.zhong.blog.pojo.Pwd;
import com.zhong.blog.pojo.User;
import com.zhong.blog.service.UserService;
import com.zhong.blog.service.auth.AuthUser;
import com.zhong.blog.utlis.R;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.PastOrPresent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/setting")
public class SettingController {

    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    /**
     * 基本设置请求
     * @param user
     * @param bindingResult
     * @return
     */
    @PostMapping("/modify")
    public R modify(@RequestBody @Valid User user, BindingResult bindingResult){
        //  数据校验
        User byId = userService.findById(user.getId());
        if (byId.equals(user)){
            return R.error().put("error","没有修改属性值");
        }
        if (!user.getUsername().equals(byId.getUsername())) {
            List<User> users = userService.queryAll();
            for (User queryUser : users) {
                if (user.getUsername().equals(queryUser.getUsername())) {
                    return R.error().put("error", "用户名已注册");
                }
            }
        }
        if (bindingResult.hasErrors()){
            System.out.println("校验错误");
            Map<String,String> map=new HashMap<>();
            bindingResult.getFieldErrors().forEach((item)->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
            System.out.println(map.toString());
            return R.error("提交数据不合法").put("error",map);
        }
        // 校验通过处理
        int count = userService.update(user);
        if (count == 1){
            System.out.println("更新成功");
        }
        // 更新token
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        String role = "admin"; // 角色名
        authorities.add(new SimpleGrantedAuthority(role));
        String encode = passwordEncoder.encode(user.getPassword());
        AuthUser root = new AuthUser(user.getUsername(), encode, authorities);
        //取得账号信息
        UserDetails userDetails = (UserDetails) root;
        String token = jwtTokenUtil.generateToken(userDetails);
        //把新的token存储到缓存中
        TokenCache.setToken(userDetails.getUsername(),token);

        return R.ok().put("token",token);
    }

    /**
     * 进入页面获取数据请求
     * @param username
     * @return
     */
    @GetMapping("/getData")
    public R getData(@RequestParam("username")  String username){
        User user = new User();
        List<User> users = userService.queryByName(username);
        if (users.size() == 1){
            user = users.get(0);
        }
        return R.ok().put("user",user);
    }

    @PostMapping("/pwd")
    public R pwd(@RequestBody @Valid Pwd pwd, BindingResult bindingResult, @RequestParam("userid") int userid){
        System.out.println(pwd.toString());
        System.out.println(userid);
        User byId = userService.findById(userid);
        // 校验
        if (bindingResult.hasErrors()){
            System.out.println("校验错误");
            Map<String,String> map=new HashMap<>();
            bindingResult.getFieldErrors().forEach((item)->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
            System.out.println(map.toString());
            return R.error("提交数据不合法").put("error",map);
        }
        // 原始密码不正确
        if (!pwd.getOldPassword().equals(byId.getPassword())){
            return R.error().put("error","原始密码不正确");
        }
        // 确认密码不一致
        if (!pwd.getNewPassword().equals(pwd.getAgainPassword())){
            return R.error().put("error","确认密码不一致");
        }
        // 更新
        byId.setPassword(pwd.getNewPassword());
        int update = userService.update(byId);
        if (update == 1){
            // 更新token
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            String role = "admin"; // 角色名
            authorities.add(new SimpleGrantedAuthority(role));
            String encode = passwordEncoder.encode(byId.getPassword());
            AuthUser root = new AuthUser(byId.getUsername(), encode, authorities);
            //取得账号信息
            UserDetails userDetails = (UserDetails) root;
            String token = jwtTokenUtil.generateToken(userDetails);
            //把新的token存储到缓存中
            TokenCache.setToken(userDetails.getUsername(),token);
            return R.ok().put("token",token);
        }else {
            return R.error().put("error","更新失败");
        }

    }


}
